﻿using DevExpress.DocumentServices.ServiceModel.DataContracts;
using OnlineQC.CommomControl;
using OnlineQC.CommomControl.CommonForms;
using OnlineQC.CommomModule;
using OnlineQC.Globalization;
using OnlineQC.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OnlineQC.SubForms
{
    public partial class MeasureParameterFrm : FrmBase
    {
        List<CustomParameterFormat> listCustomParameterFormat = new List<CustomParameterFormat>();
        public MeasureParameterFrm()
        {
            InitializeComponent();
        }

        private void MeasureParameterFrm_Load(object sender, EventArgs e)
        {
            SetControlStatus(ActionStatus.Init);

            listCustomParameterFormat = QueryCustomParameters();
            gcCustomParameter.DataSource = CustomParameters(listCustomParameterFormat);
            gcCustomParameter.RefreshDataSource();

            gcParameter.DataSource = ParameterHelper.GetParameterTypes();
            gcParameter.RefreshDataSource();
        }
        private List<DictionaryBase> CustomParameters(List<CustomParameterFormat> listCustomParameterFormat )
        {
            List<DictionaryBase> listDictionaryBase = new List<DictionaryBase>();
            foreach (CustomParameterFormat customParameterFormat in listCustomParameterFormat)
            {
                listDictionaryBase.Add(new DictionaryBase()
                {
                    index = customParameterFormat.ParametersNumber,
                    key = customParameterFormat.ParametersNumber,
                    value = customParameterFormat.ParametersDescription,
                });
            }
            return listDictionaryBase;
        }
        /// <summary>
        /// 获取自定参数
        /// </summary>
        /// <returns></returns>
        private List<CustomParameterFormat> QueryCustomParameters()
        {
            try
            {
                //获取 自定参数文件
                if (!FileHelper.FileExists(Global.applicationSetting.CustomParameterPath))
                {
                    FileHelper.CreateFile(Global.applicationSetting.CustomParameterPath);

                    return new List<CustomParameterFormat>();
                }

                string content = File.ReadAllText(Global.applicationSetting.CustomParameterPath);
                List<CustomParameterFormat> listCustomParameterFormat = JsonHelper.DeserializeJsonToObject<List<CustomParameterFormat>>(content);
                return listCustomParameterFormat;
            }
            catch (Exception ex)
            {
                FrmShowHelper.ShowMessage(ex.Message);
                return null;
            }
        }

        ActionStatus actionStatus;
        private void SetControlStatus(ActionStatus status)
        {
            actionStatus = status;

            if (ActionStatus.Init == status)
            {
                btnAddCustomParameter.Enabled = true;
                btnUpdateCustomParameter.Enabled = false;
                btnSure.Enabled = false;
                btnDeleteCustomParameter.Enabled = false;

                txtParameterName.ReadOnly = true;
                txtParameterName.Enabled = false;
                txtParameterFormula.ReadOnly = true;
                txtParameterFormula.Enabled = false;
            }
            else if (ActionStatus.Choosed == status)
            {
                btnAddCustomParameter.Enabled = true;
                btnUpdateCustomParameter.Enabled = true;
                btnSure.Enabled = false;
                btnDeleteCustomParameter.Enabled = true;

                txtParameterName.ReadOnly = true;
                txtParameterName.Enabled = false;
                txtParameterFormula.ReadOnly = true;
                txtParameterFormula.Enabled = false;
            }
            else if (ActionStatus.Insert == status)
            {
                btnSure.Enabled = true;

                txtParameterName.ReadOnly = false;
                txtParameterName.Enabled = true;
                txtParameterFormula.ReadOnly = false;
                txtParameterFormula.Enabled = true;
            }
            else if (ActionStatus.Update == status)
            {
                btnSure.Enabled = true;

                txtParameterName.ReadOnly = false;
                txtParameterName.Enabled = true;
                txtParameterFormula.ReadOnly = false;
                txtParameterFormula.Enabled = true;

            }
            else if (ActionStatus.delete == status)
            {
                //btnSure.Enabled = true;

                //txtParameterName.ReadOnly = false;
                //txtParameterName.Enabled = true;
                //txtParameterFormula.ReadOnly = false;
                //txtParameterFormula.Enabled = true;
            }
            else if (ActionStatus.Sure == status)
            {
                btnAddCustomParameter.Enabled = true;
                btnUpdateCustomParameter.Enabled = true;

                txtParameterName.ReadOnly = true;
                txtParameterName.Enabled = false;
                txtParameterFormula.ReadOnly = true;
                txtParameterFormula.Enabled = false;
            }
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddCustomParameter_Click(object sender, EventArgs e)
        {
            txtParameterName.Text = "";
            txtParameterFormula.Text = "";
            SetControlStatus(ActionStatus.Insert);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdateCustomParameter_Click(object sender, EventArgs e)
        {
            SetControlStatus(ActionStatus.Update);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDeleteCustomParameter_Click(object sender, EventArgs e)
        {
            try
            {
                if (gvCustomParameter.RowCount <=0 )
                {
                    return;
                }
                DictionaryBase dictionaryBase = gvCustomParameter.GetFocusedRow() as DictionaryBase;

                List<CustomParameterFormat>  list=listCustomParameterFormat.Where(o=>o.ParametersNumber == (int)dictionaryBase.key).ToList();
                foreach (CustomParameterFormat format in list) {
                    listCustomParameterFormat.Remove(format);
                }

                gcCustomParameter.DataSource = CustomParameters(listCustomParameterFormat);
                gcCustomParameter.RefreshDataSource();
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除失败！".ToMultiLanguage() + ex.Message);
            }
        }
        /// <summary>
        ///保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSure_Click(object sender, EventArgs e)
        {
            try
            {
                string name = txtParameterName.Text;
                if (string.IsNullOrEmpty(name))
                {
                    MessageBox.Show("名称不能为空！".ToMultiLanguage());
                    return;
                }
                string formula = txtParameterFormula.Text.Trim();
                if (string.IsNullOrEmpty(formula))
                {
                    MessageBox.Show("参数公式不能为空！".ToMultiLanguage());
                    return;
                }
                if (ParameterHelper.CheckFormula(formula) == -1)
                {
                    MessageBox.Show("填写的参数公式有误".ToMultiLanguage());
                    return;
                }
                //删除再新增

                if (actionStatus == ActionStatus.Insert)
                {
                    int parameterNumber = listCustomParameterFormat.Count + 100;
                    listCustomParameterFormat.Add(new CustomParameterFormat()
                    {
                        ParametersNumber = parameterNumber,
                        ParametersType = name,
                        ParametersName = name,
                        ParametersDescription = name,
                        ChildParameterCount = 1,
                        ChildParameterNames = new List<string>() { name },
                        ChildParameterDescription = "",
                        CustomParameterFormula = formula,
                        IsUsing = 1,
                    });
                }
                else if (actionStatus == ActionStatus.Update)
                {
                    if (listCustomParameterFormat != null && listCustomParameterFormat.Count > 0)
                    {
                        DictionaryBase dictionaryBase = gvCustomParameter.GetFocusedRow() as DictionaryBase;
                        List<CustomParameterFormat> customParameterFormats = listCustomParameterFormat.Where(o => o.ParametersNumber == (int)dictionaryBase.key).ToList();
                        customParameterFormats.ForEach(o =>
                        {
                            o.ParametersType = name;
                            o.ParametersName = name;
                            o.ParametersDescription = name;
                            o.ChildParameterNames = new List<string>() { name };
                            o.CustomParameterFormula = formula;
                        });
                    }
                }

                SaveCustomParameters();

                gcCustomParameter.DataSource = CustomParameters(listCustomParameterFormat);
                gcCustomParameter.RefreshDataSource();
                MessageBox.Show("保存成功！".ToMultiLanguage());
            }
            catch (Exception ex)
            {
                //LogHelper.Error(ex.Message);
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 获取自定参数
        /// </summary>
        /// <returns></returns>
        private void SaveCustomParameters()
        {
            try
            {
                //获取 自定参数文件
                if (!FileHelper.FileExists(Global.applicationSetting.CustomParameterPath))
                {
                    FileHelper.CreateFile(Global.applicationSetting.CustomParameterPath);

                }
                string content =  JsonHelper.SerializeObject(listCustomParameterFormat);

                File.WriteAllText(content, Global.applicationSetting.CustomParameterPath);
            }
            catch (Exception ex)
            {
                throw new Exception("保存失败！".ToString() +ex.Message); 
            }
        }
        private void MeasureParameterFrm_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                //关闭窗口前保存参数
                SaveCustomParameters();
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message);
            }
        }

        private void gvCustomParameter_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (gvCustomParameter != null && gvCustomParameter.RowCount > 0)
            {

                DictionaryBase dictionaryBase = gvCustomParameter.GetFocusedRow() as DictionaryBase;

                CustomParameterFormat customParameterFormat = listCustomParameterFormat.Find(o => o.ParametersNumber == (int)dictionaryBase.key);

                txtParameterName.Text = customParameterFormat.ParametersName;
                txtParameterFormula.Text = customParameterFormat.CustomParameterFormula;
                txtChooseParameter.Text = customParameterFormat.ParametersName;
                SetControlStatus(ActionStatus.Choosed);
            }
          
        }

        private void gvParameter_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (gvCustomParameter == null || gvCustomParameter.RowCount < 0)
            {
                return;
            }

            DictionaryBase dictionaryBase = gvParameter.GetFocusedRow() as DictionaryBase;
            txtChooseParameter.Text = dictionaryBase.value.ToString();
        }
    }
    public enum ActionStatus
    {
        //初始状态
        Init,
        //选择
        Choosed,
        //新增
        Insert,
        //更新
        Update,
        //删除
        delete,
        //确认
        Sure
    }
}
